package com.boarsoft.message.amq.plugin;

import java.util.HashMap;
import java.util.Map;

import org.apache.activemq.broker.Broker;
import org.apache.activemq.broker.BrokerPlugin;
import org.apache.activemq.command.Message;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.boarsoft.message.amq.adapter.AmqMsgConverter;
import com.boarsoft.message.core.MessageService;

/**
 * 
 * @author Mac_J
 *
 */
public class InterceptorPlugin implements BrokerPlugin {
	private static final Logger log = LoggerFactory.getLogger(InterceptorPlugin.class);

	protected MessageService messageService;
	protected Map<String, AmqMsgConverter> converterMap = new HashMap<String, AmqMsgConverter>();

	@Override
	public Broker installPlugin(Broker broker) throws Exception {
		return new InterceptorFilter(broker, this);
	}

	/**
	 * 
	 * @param am
	 *            ActiveMQ message
	 * @return 返回true表示不处理，由AMQ继续处理
	 * @throws Exception
	 */
	public boolean put(Message am) throws Exception {
		String dpn = am.getDestination().getPhysicalName();
		log.info("Intercept AMQ message {} {}", am.getClass().getName(), dpn);
		AmqMsgConverter amc = converterMap.get(dpn);
		if (amc == null) {
			return true;
		}
		messageService.put(amc.convert(am));
		return false;
	}

	public MessageService getMessageService() {
		return messageService;
	}

	public void setMessageService(MessageService messageService) {
		this.messageService = messageService;
	}

	public Map<String, AmqMsgConverter> getConverterMap() {
		return converterMap;
	}

	public void setConverterMap(Map<String, AmqMsgConverter> converterMap) {
		this.converterMap = converterMap;
	}
}
